import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import home from '../views/home.vue'
import welcome from '../views/Welcome.vue'
import users from '../views/user/Users.vue'
import rights from '../views/power/Rights.vue'
import roles from '../views/power/Roles.vue'
import cate from '../views/goods/Cate.vue'
import params from '../views/goods/Params.vue'
import goodslist from '../views/goods/List.vue'
import add from '../views/goods/Add.vue'
import order from '../views/order/Order.vue'
import report from '../views/report/Report.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/home',
    name: 'home',
    component: home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: welcome
      },
      {
        path: '/rights',
        component: rights
      },
      {
        path: '/users',
        component: users
      },
      {
        path: '/roles',
        component: roles
      },
      {
        path: '/categories',
        component: cate
      },
      {
        path: '/params',
        component: params
      },
      {
        path: '/goods',
        component: goodslist
      },
      {
        path: '/goods/add',
        component: add
      },
      {
        path: '/orders',
        component: order
      },
      {
        path: '/reports',
        component: report
      },
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to:访问路径 from:跳转来源路径 next:放行函数
  if(to.path === '/login') {
    return next()
  }else{
    const tokenStr = window.sessionStorage.getItem('token');
    console.log(tokenStr);
    // token 不存在,强制跳转到 /login
    if(!tokenStr){
      return next('/login')
    }else{
      next()
    }
  }
})

export default router
